package cn.bqjr.eily.web.utils;

import cn.bqjr.eily.core.utils.SysConfigUtils;
import cn.bqjr.eily.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * Web工具类
 * Created by hp on 2017/5/11.
 */
public class WebUtils {

    private static List<String> ipHeaderList = Arrays.asList("x-forwarded-for", "Proxy-Client-IP",
            "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR");

    private static final String REQUEST_DEBUG = "debugMode";

    /**
     * 判断是否为ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("x-requested-with");
        return (StringUtils.isNotEmpty(header) && "XMLHttpRequest".endsWith(header));
    }

    /**
     * 获取访问者IP地址
     *
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public static String getIpAddr(HttpServletRequest request) {
        String remoteIp = request.getRemoteAddr();
        return ipHeaderList.stream().filter(header -> {
            String ip = request.getHeader(header);
            return (StringUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip));
        }).findFirst().orElse(StringUtils.isEmpty(remoteIp) ? "unknown" : remoteIp);
    }

    public static boolean isDebugMode(HttpServletRequest request) {
        String reqDebug = request.getParameter(REQUEST_DEBUG);
        if (StringUtils.isBlank(reqDebug)) {
            return SysConfigUtils.isDebugMode();
        }
        return Boolean.valueOf(reqDebug);
    }
}
